<template>
  <div class="home">
    <fixedsearch ref="search" :showFixed="showFixed"></fixedsearch>
    <search ref="advancedSearch"></search>
    <div class="main" ref="mainWrapper">
      <div class="mainContent">
        <div class="swipe-wrapper swipe-hook">
          <swipe :swiperSlides="swiperSlides"></swipe>
        </div>
        <topchanel :channels="channels"></topchanel>
        <modal-title title="商城入口、优惠券" catKey="" catName=""></modal-title>
        <div class="wx_follow">
          <img :src="wxqrcode2" border="0" @click.stop.prevent="previewQrcode2" />
        </div>
        <split></split>
        <div v-for="(item, index) in channelGoods" :key="index">
          <modal-title :title="item.title" moreText="更多" catKey="" catName="" price=""></modal-title>
          <channel :items="item.goods" :cols="2" :section="item.key"></channel>
          <split></split>
        </div>
        <modal-title title="轻奢好茶" moreText="更多" catKey="welltea" catName="轻奢好茶"></modal-title>
        <channel :items="goodTeas" :cols="2" section="nicetea"></channel>
        <split v-show="oldcollect.length"></split>
        <modal-title title="古树.经典酵藏普洱" moreText="更多" catKey="oldcollect" catName="古树.经典酵藏普洱" v-show="oldcollect.length"></modal-title>
        <channel :items="oldcollect" :cols="2" section="oldcollect"></channel>
        <split v-if="oldTeas.length"></split>
        <modal-title title="老茶专区" moreText="更多" catKey="museum" catName="老茶专区" v-if="oldTeas.length"></modal-title>
        <channel :items="oldTeas" :cols="2" section="tealab"></channel>
        <split v-show="singleBubble.length"></split>
        <modal-title title="单泡购专区(50元包邮)" moreText="更多" catKey="singlebubble" catName="单泡购专区(50元包邮)" v-show="singleBubble.length"></modal-title>
        <channel :items="singleBubble" :cols="2" section="singlebubble"></channel>
        <split></split>
        <modal-title title="茶器雅物(1000元以内)" moreText="更多" catKey="teaart" catName="茶器雅物(1000元以内)" price="0-1000"></modal-title>
        <channel :items="teaPots" :cols="2" section="cheap_teaware"></channel>
        <split></split>
        <modal-title title="茶器雅物(1000元以上)" moreText="更多" catKey="teaart" catName="茶器雅物(1000元以上)" price="1000-"></modal-title>
        <channel :items="dearTeapots" :cols="2" section="dearly_teaware"></channel>
        <split></split>
        <modal-title title="茶席套装" moreText="更多" catKey="art" catName="茶席套装"></modal-title>
        <channel :items="arts" :cols="2" section="teasuite"></channel>
        <split></split>
        <section-title title='博览集萃 (茶.雅生活)' v-show="articles && articles.length" moreText="更多" :getMore="getMoreArticles"></section-title>
        <split v-show="articles && articles.length"></split>
        <articlelist :articles="articles" v-show="articles && articles.length" section="articles"></articlelist>
        <split v-if="showFollow"></split>
        <modal-title :title="aboutUs" catKey="" catName="" v-show="showFollow"></modal-title>
        <div v-if="showFollow" class="wx_follow">
          <img :src="wxqrcode" border="0" @click.stop.prevent="previewQrcode" />
        </div>
      </div>
    </div>
    <gotop ref="top" @top="goTop" :scrollY="scrollY"></gotop>
    <quietlogin></quietlogin>
  </div>
</template>

<script type="text/ecmascript-6">
  import BScroll from 'better-scroll';
  import fixedsearch from '@/components/fixedtoolbar/fixedsearch';
  import swipe from '@/components/swipe/swipe';
  import topchanel from '@/components/channel/topchanelv2';
  import split from '@/components/split/split';
  import modalTitle from '@/components/modal-title/modal-title';
  import sectionTitle from '@/components/common/section-title';
  import channel from '@/components/channel/channel';
  import gotop from '@/components/fixedtoolbar/gotop';
  import search from '@/components/fixedtoolbar/search';
  import articlelist from '@/components/article/articlelist';
  import quietlogin from '@/components/common/quietlogin';
  import api from '@/api/api';
  import wx from 'weixin-js-sdk';

  export default {
    data() {
      return {
        scrollY: 0,
        articles: [],
        arts: [],
        teaPots: [],
        dearTeapots: [],
        goodTeas: [],
        oldTeas: [],
        oldcollect: [],
        paints: [],
        ya: [],
        channelGoods: [],
        singleBubble: [],
        channels: [{
          name: '轻奢好茶',
          url: '/search?parentCat=welltea&key=轻奢好茶',
          icon: 'icon-tea_drink big'
        }, {
          name: '古树.酵藏',
          url: '/search?parentCat=oldcollect&key=古树.酵藏',
          icon: 'icon-funds big'
        }, {
          name: '老茶专区',
          url: '/search?parentCat=museum&key=老茶专区',
          icon: 'icon-museum big'
        }, {
          name: '单泡购专区',
          url: '/search?parentCat=singlebubble&key=单泡购专区',
          icon: 'icon-teapot_and_cup big'
        }, {
          name: '茶器雅物',
          url: '/search?parentCat=teaart&key=茶器雅物',
          icon: 'icon-blackteapot big'
        }, {
          name: '我的存茶',
          url: '/mystore',
          icon: 'icon-shopping_bag'
        }, {
          name: '首单5-7折',
          url: '/firstpurchase',
          icon: 'icon-prefer big',
          highlight: true
        }, {
          name: '砍价区',
          url: '/sharepay',
          icon: 'icon-cutingprice big',
          highlight: true
        }, {
          name: '拼团5-7折',
          url: '/tuan',
          icon: 'icon-tuan big',
          highlight: true
        }, {
          name: '秒 杀',
          url: '/seckill',
          icon: 'icon-miaosha big'
        }, {
          name: '团 购',
          url: '/groupbuy',
          icon: 'icon-group_purchase',
          css: 'nobottom'
        }, {
          name: '拍 卖',
          url: '/auction',
          icon: 'icon-auction',
          css: 'nobottom'
        }, {
          name: '文 章',
          url: '/articles',
          icon: 'icon-file'
        }, {
          name: '茶 书',
          url: '/search?parentCat=chaS&key=茶书',
          icon: 'icon-diamond big'
        }, {
          name: '茶修/活动',
          url: '/activities',
          icon: 'icon-dancers'
        }],
        swiperSlides: [
          'http://xiaochaguan.yihuyixi.com/ps/download/5a352b80e4b04d4e77f2da59?h=500',
          'http://xiaochaguan.yihuyixi.com/ps/download/5a352b7de4b04d4e77f2da57?h=500',
          'http://xiaochaguan.yihuyixi.com/ps/download/5a352b81e4b04d4e77f2da5a?h=500'
        ],
        selectedGood: {},
        showTop: false,
        swipeHeight: 0,
        lastInitPlayer: +new Date(),
        videos: {
          'vip': 'http://1252423336.vod2.myqcloud.com/950efb46vodtransgzp1252423336/85f5db404564972818869478317/v.f20.mp4',
          'spring': 'http://1252423336.vod2.myqcloud.com/950efb46vodtransgzp1252423336/85f5d37d4564972818869478170/v.f20.mp4'
        },
        showFollow: true,
        wxqrcode: api.CONFIG.wxqrcode,
        wxqrcode2: api.CONFIG.wxqrcode2,
        coins: {
          coin: 0,
          yourCoin: 0
        }
      };
    },
    created() {
      // 性能优化，增加首页本地缓存
      let appCache = this.$store.getters.loadAppCache || {};
      if (appCache.home && appCache.home.arts && appCache.home.arts.length) {
        console.log('cache hit.');
        let hitCache = appCache.home;
        this.arts = hitCache.arts || [];
        this.dearTeapots = hitCache.dearTeapots || [];
        this.teaPots = hitCache.teaPots || [];
        this.goodTeas = hitCache.goodTeas || [];
        this.oldTeas = hitCache.oldTeas || [];
        this.articles = hitCache.articles || [];
        this.oldcollect = hitCache.oldcollect || [];
        this.singleBubble = hitCache.singleBubble || [];
        this.channelGoods = hitCache.channelGoods || [];
        setTimeout(() => {
          this.fetchData();
        }, 3000);
      } else {
        this.fetchData();
      }
      this.wxReady();
    },
    mounted() {
      this.scroller = this.$refs.mainWrapper;
      window.addEventListener('scroll', this._handleScroll);
    },
    deactivated() {
      window.removeEventListener('scroll', this._handleScroll);
      this.coins = {
        coin: 0,
        yourCoin: 0
      };
    },
    updated() {
      this._initScroll();
    },
    activated() {
      // this.fetchData();
      this._initScroll();
      window.removeEventListener('scroll', this._handleScroll);
      window.addEventListener('scroll', this._handleScroll);
    },
    computed: {
      showFixed() {
        return this.scrollY >= this.swipeHeight;
      },
      getVideoWidth() {
        let w = document.documentElement.clientWidth;
        return { width: w + 'px', height: w * 0.575 + 'px' };
      },
      aboutUs() {
        return `关于「${api.CONFIG.APPNAME || '一虎一席茶生活美学商城'}」`;
      }
    },
    methods: {
      fetchData() {
        let user = this.$store.getters.getUserInfo;
        let anon = '';
        if (!user.userId) {
          this.$store.dispatch('setAnonymous');
          anon = this.$store.getters.getAnonymous;
        }
        api.getHomeList({
          type: 'home',
          stat: 1,
          unlogin: anon
        }).then((response) => {
          this.channelGoods = [];
          for (let key in response) {
            if (key.length > 20) {
              if (response[key] && response[key].goods && response[key].title) {
                this.channelGoods.push({'key': key, 'title': response[key].title, 'goods': response[key].goods});
              }
            }
          }
          this.arts.length = 0;
          this.dearTeapots.length = 0;
          this.teaPots.length = 0;
          this.goodTeas.length = 0;
          this.oldTeas.length = 0;
          this.articles.length = 0;
          this.oldcollect.length = 0;
          this.singleBubble.length = 0;

          this.arts = response.arts || [];
          this.dearTeapots = response.dearTeapots || [];
          this.teaPots = response.teaPots || [];
          this.goodTeas = response.goodTeas || [];
          this.oldTeas = response.oldTeas || [];
          this.articles = response.articles || [];
          this.oldcollect = response.oldcollect || [];
          this.singleBubble = response.singleBubble || [];
          if (this.arts.length && this.teaPots.length) {
            this.$store.dispatch('updateAppCache', {'home': {
              arts: this.arts,
              dearTeapots: this.dearTeapots,
              teaPots: this.teaPots,
              goodTeas: this.goodTeas,
              oldTeas: this.oldTeas,
              articles: this.articles,
              oldcollect: this.oldcollect,
              singleBubble: this.singleBubble,
              channelGoods: this.channelGoods
            }});
          }
        });
      },
      _initScroll() {
        let swipe = this.$refs.mainWrapper && this.$refs.mainWrapper.getElementsByClassName('swipe-hook') && this.$refs.mainWrapper.getElementsByClassName('swipe-hook')[0] || {};
        this.swipeHeight = swipe.clientHeight || 0;
      },
      selectGood(good) {
        this.selectedGood = good;
        this.$refs.goodDetail.show();
      },
      addFood(target) {
      },
      _initPlayer() {
      },
      getMoreArticles() {
        this.$router.push({name: 'articles'});
      },
      goTop() {
        this.scrollY = 0;
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
        // let swipe = this.$refs.mainWrapper.getElementsByClassName('swipe-hook')[0];
        // this.scroll.scrollToElement(swipe, 300);
      },
      wxReady() {
        api.wxsignature(encodeURIComponent(location.href.split('#')[0])).then(response => {
          wx.config({
            // debug: true, // 开启调试模式
            appId: response.appId,      // 必填，公众号的唯一标识
            timestamp: response.timestamp,  // 必填，生成签名的时间戳
            nonceStr: response.nonceStr,   // 必填，生成签名的随机串
            signature: response.signature,  // 必填，签名，见附录1
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
          });
        });
        let redirect = 'http://' + location.host + location.pathname;
        let uid = this.$store.getters.getUserInfo.userId;
        if (uid) {
          redirect += '?userId=' + (uid || 0);
        }
        let shareData = {
          title: '【小茶馆商城】(从此轻松买·好茶好茶器)',
          desc: '300款好茶 / 300款精美茶器 / 老茶专区 / 荟萃茶文化精华.【一站式、质优价平】',
          link: redirect,
          imgUrl: 'http://' + location.host + '/logo.png'
        };
        wx.ready(function() {
          wx.onMenuShareTimeline(shareData);
          wx.onMenuShareAppMessage(shareData);
        });
      },
      getWXFollow() {
        let user = this.$store.getters.getUserInfo;
        if (!user.userId) {
          this.showFollow = true;
          return;
        }
        api.getUserProfile(user.userId || 0).then(response => {
          if (response.result === 0 && response.user) {
            this.showFollow = (response.user.follow === 0 || response.user.follow === 2);
          }
        }).catch(response => {
          console.error(response);
        });
      },
      previewQrcode() {
        wx.previewImage({
          current: this.wxqrcode,
          urls: [this.wxqrcode]
        });
      },
      previewQrcode2() {
        wx.previewImage({
          current: this.wxqrcode2,
          urls: [this.wxqrcode2]
        });
      },
      _handleScroll(e) {
        this.scrollY = window.pageYOffset;
      }
    },
    components: {
      swipe,
      topchanel,
      split,
      modalTitle,
      channel,
      fixedsearch,
      gotop,
      search,
      articlelist,
      sectionTitle,
      quietlogin
    }
  };
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .main
    position: absolute
    left: 0
    top: 0
    bottom: 50px
    width: 100%
    .mainContent
      position: relative
      padding-bottom: 80px
      overflow: auto
      box-sizing: border-box
      -webkit-overflow-scrolling: touch
      background-color: #fff
      #tencent_video_player, #vip_video_player
        position: relative
        width: 100%
        height: auto
        padding: 0 5px
        box-sizing: border-box
        overflow: hidden
      .slogan
        line-height: 1.5
        font-size: 14px
        padding: 3px 8px
        white-space: normal
        word-break: break-all
        -webkit-line-clamp: 2
        -webkit-box-orient: vertical
        text-overflow: ellipsis
        overflow: hidden
      .vipmovie, .aboutus
        padding-bottom: 8px
    .swipe-wrapper
      position: relative
      width: 100%
      height: auto
      margin: 0 auto
  .wx_follow
    position: relative
    width: 100%
    height: auto
    overflow: hidden
    img
      position: relative
      width: 100%
      height: auto
</style>
